// 知识库管理页面 JavaScript 功能
class KnowledgeBaseApp {
    constructor() {
        this.initElements();
        this.bindEvents();
        this.loadDocuments();
        this.currentDeleteId = null;
    }

    initElements() {
        // 文件上传相关
        this.uploadArea = document.getElementById('uploadArea');
        this.fileInput = document.getElementById('fileInput');
        this.uploadBtn = document.getElementById('uploadBtn');
        this.uploadProgress = document.getElementById('uploadProgress');
        this.progressFill = document.getElementById('progressFill');
        this.progressText = document.getElementById('progressText');

        // 搜索相关
        this.searchInput = document.getElementById('searchInput');
        this.searchBtn = document.getElementById('searchBtn');
        this.topKInput = document.getElementById('topK');
        this.scoreThresholdInput = document.getElementById('scoreThreshold');
        this.searchResults = document.getElementById('searchResults');

        // 文档列表相关
        this.documentsTableBody = document.getElementById('documentsTableBody');
        this.documentsLoading = document.getElementById('documentsLoading');
        this.emptyState = document.getElementById('emptyState');
        this.refreshBtn = document.getElementById('refreshBtn');

        // 功能按钮相关
        this.openUploadModal = document.getElementById('openUploadModal');
        this.openSearchModal = document.getElementById('openSearchModal');

        // 模态框相关
        this.uploadModal = document.getElementById('uploadModal');
        this.searchModal = document.getElementById('searchModal');
        this.deleteModal = document.getElementById('deleteModal');
        this.detailModal = document.getElementById('detailModal');
        this.deleteFileName = document.getElementById('deleteFileName');
        this.uploadModalClose = document.getElementById('uploadModalClose');
        this.searchModalClose = document.getElementById('searchModalClose');
        this.modalClose = document.getElementById('modalClose');
        this.detailModalClose = document.getElementById('detailModalClose');
        this.cancelDelete = document.getElementById('cancelDelete');
        this.confirmDelete = document.getElementById('confirmDelete');

        // 消息提示
        this.toast = document.getElementById('toast');
        
        // 检查关键元素是否存在
        const requiredElements = [
            'uploadArea', 'fileInput', 'uploadBtn', 'documentsTableBody', 
            'documentsLoading', 'emptyState', 'toast'
        ];
        
        for (const elementName of requiredElements) {
            if (!this[elementName]) {
                console.error(`Required element not found: ${elementName}`);
            }
        }
    }

    bindEvents() {
        // 文件上传事件
        this.uploadBtn.addEventListener('click', (e) => {
            e.stopPropagation(); // 阻止事件冒泡
            this.fileInput.click();
        });
        this.fileInput.addEventListener('change', (e) => this.handleFileSelect(e));
        
        // 拖拽上传事件
        this.uploadArea.addEventListener('dragover', (e) => this.handleDragOver(e));
        this.uploadArea.addEventListener('dragleave', (e) => this.handleDragLeave(e));
        this.uploadArea.addEventListener('drop', (e) => this.handleDrop(e));
        this.uploadArea.addEventListener('click', (e) => {
            // 只有当点击的不是按钮时才触发文件选择
            if (e.target !== this.uploadBtn && !this.uploadBtn.contains(e.target)) {
                this.fileInput.click();
            }
        });

        // 搜索事件
        this.searchBtn.addEventListener('click', () => this.performSearch());
        this.searchInput.addEventListener('keydown', (e) => {
            if (e.key === 'Enter') {
                this.performSearch();
            }
        });

        // 刷新按钮
        this.refreshBtn.addEventListener('click', () => this.loadDocuments());

        // 功能按钮事件
        this.openUploadModal.addEventListener('click', () => this.showUploadModal());
        this.openSearchModal.addEventListener('click', () => this.showSearchModal());

        // 模态框事件
        this.uploadModalClose.addEventListener('click', () => this.hideUploadModal());
        this.searchModalClose.addEventListener('click', () => this.hideSearchModal());
        this.modalClose.addEventListener('click', () => this.hideDeleteModal());
        this.detailModalClose.addEventListener('click', () => this.hideDetailModal());
        this.cancelDelete.addEventListener('click', () => this.hideDeleteModal());
        this.confirmDelete.addEventListener('click', () => this.deleteDocument());

        // 点击模态框背景关闭
        this.uploadModal.addEventListener('click', (e) => {
            if (e.target === this.uploadModal) {
                this.hideUploadModal();
            }
        });
        this.searchModal.addEventListener('click', (e) => {
            if (e.target === this.searchModal) {
                this.hideSearchModal();
            }
        });

        // 点击模态框外部关闭
        this.deleteModal.addEventListener('click', (e) => {
            if (e.target === this.deleteModal) {
                this.hideDeleteModal();
            }
        });

        // ESC键关闭弹框
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                if (this.uploadModal.style.display === 'flex') {
                    this.hideUploadModal();
                } else if (this.searchModal.style.display === 'flex') {
                    this.hideSearchModal();
                } else if (this.deleteModal.style.display === 'flex') {
                    this.hideDeleteModal();
                }
            }
        });
    }

    // 文件拖拽处理
    handleDragOver(e) {
        e.preventDefault();
        this.uploadArea.classList.add('dragover');
    }

    handleDragLeave(e) {
        e.preventDefault();
        this.uploadArea.classList.remove('dragover');
    }

    handleDrop(e) {
        e.preventDefault();
        this.uploadArea.classList.remove('dragover');
        const files = e.dataTransfer.files;
        this.uploadFiles(files);
    }

    // 文件选择处理
    handleFileSelect(e) {
        const files = e.target.files;
        this.uploadFiles(files);
    }

    // 文件上传
    async uploadFiles(files) {
        if (!files || files.length === 0) return;

        for (let i = 0; i < files.length; i++) {
            await this.uploadSingleFile(files[i]);
        }
        
        // 重置文件输入
        this.fileInput.value = '';
        // 刷新文档列表
        this.loadDocuments();
    }

    async uploadSingleFile(file) {
        // 检查文件类型
        const allowedTypes = ['.pdf', '.doc', '.docx', '.txt', '.md'];
        const fileExtension = '.' + file.name.split('.').pop().toLowerCase();
        
        if (!allowedTypes.includes(fileExtension)) {
            this.showToast('不支持的文件类型: ' + file.name, 'error');
            return;
        }

        // 检查文件大小 (限制为50MB)
        if (file.size > 50 * 1024 * 1024) {
            this.showToast('文件过大: ' + file.name + ' (最大50MB)', 'error');
            return;
        }

        const formData = new FormData();
        formData.append('file', file);

        try {
            this.showUploadProgress(true);
            this.updateProgress(0);

            const response = await fetch('/ai/document/upload', {
                method: 'POST',
                body: formData
            });

            if (response.ok) {
                const result = await response.json();
                if (result.code === 200) {
                    this.updateProgress(100);
                    this.showToast('文件上传成功: ' + file.name, 'success');
                } else {
                    throw new Error(result.msg || '上传失败');
                }
            } else {
                throw new Error('上传请求失败');
            }
        } catch (error) {
            console.error('Upload error:', error);
            this.showToast('上传失败: ' + error.message, 'error');
        } finally {
            setTimeout(() => {
                this.showUploadProgress(false);
            }, 1000);
        }
    }

    // 显示/隐藏上传进度
    showUploadProgress(show) {
        this.uploadProgress.style.display = show ? 'block' : 'none';
    }

    // 更新上传进度
    updateProgress(percent) {
        this.progressFill.style.width = percent + '%';
        this.progressText.textContent = percent + '%';
    }

    // 执行搜索
    async performSearch() {
        const query = this.searchInput.value.trim();
        if (!query) {
            this.showToast('请输入搜索关键词', 'warning');
            return;
        }

        const topK = this.topKInput.value.trim();
        const scoreThreshold = this.scoreThresholdInput.value.trim();

        try {
            this.searchBtn.disabled = true;
            this.searchBtn.innerHTML = '搜索中...';

            // 构建搜索参数，只包含有值的参数
            const params = new URLSearchParams();
            params.append('query', query);
            
            // 只有当用户输入了具体值时才添加参数
            if (topK && topK !== '' && !isNaN(topK) && parseInt(topK) > 0) {
                params.append('topK', topK);
            }
            
            if (scoreThreshold && scoreThreshold !== '' && !isNaN(scoreThreshold)) {
                params.append('scoreThreshold', scoreThreshold);
            }

            const response = await fetch(`/vector/test/search?${params}`);
            
            if (response.ok) {
                const result = await response.json();
                if (result.code === 200) {
                    this.displaySearchResults(result.data);
                    this.showToast(`找到 ${result.data.length} 条相关结果`, 'success');
                } else {
                    throw new Error(result.msg || '搜索失败');
                }
            } else {
                throw new Error('搜索请求失败');
            }
        } catch (error) {
            console.error('Search error:', error);
            this.showToast('搜索失败: ' + error.message, 'error');
        } finally {
            this.searchBtn.disabled = false;
            this.searchBtn.innerHTML = '搜索';
        }
    }

    // 显示搜索结果
    displaySearchResults(results) {
        this.searchResults.style.display = 'block';
        
        if (!results || results.length === 0) {
            this.searchResults.innerHTML = `
                <div class="empty-state">
                    <h3>未找到相关内容</h3>
                    <p>请尝试其他关键词或调整搜索参数</p>
                </div>
            `;
            return;
        }

        const resultsHtml = results.map((result, index) => `
            <div class="search-result-item">
                <div class="search-result-header">
                    <div class="search-result-title">
                        <span class="result-index">${index + 1}.</span>
                        <strong>${result.metadata?.fileName || '未知文档'}</strong>
                    </div>
                    <div class="search-result-scores">
                        <span class="search-result-score" title="相似度分数">
                            相似度: ${(result.score || 0).toFixed(3)}
                        </span>
                        <span class="search-result-distance" title="向量距离">
                            距离: ${(result.metadata?.distance || 0).toFixed(3)}
                        </span>
                    </div>
                </div>
                <div class="search-result-content">
                    ${this.highlightSearchTerms(result.text || '', this.searchInput.value)}
                </div>
                <div class="search-result-meta">
                    <span class="meta-item">文档ID: ${result.id}</span>
                    ${result.metadata?.source ? `<span class="meta-item">来源: ${result.metadata.source}</span>` : ''}
                </div>
            </div>
        `).join('');

        this.searchResults.innerHTML = resultsHtml;
    }

    // 高亮搜索关键词
    highlightSearchTerms(content, searchTerm) {
        if (!searchTerm) return content;
        
        const regex = new RegExp(`(${searchTerm})`, 'gi');
        return content.replace(regex, '<mark>$1</mark>');
    }

    // 加载文档列表
    async loadDocuments() {
        try {
            this.showDocumentsLoading(true);
            
            const response = await fetch('/ai/document/list');
            
            if (response.ok) {
                const result = await response.json();
                if (result.code === 200) {
                    this.displayDocuments(result.data);
                } else {
                    throw new Error(result.msg || '加载文档列表失败');
                }
            } else {
                throw new Error('请求失败');
            }
        } catch (error) {
            console.error('Load documents error:', error);
            this.showToast('加载文档列表失败: ' + error.message, 'error');
            this.showEmptyState(true);
        } finally {
            this.showDocumentsLoading(false);
        }
    }

    // 显示文档列表
    displayDocuments(documents) {
        if (!documents || documents.length === 0) {
            this.showEmptyState(true);
            return;
        }

        this.showEmptyState(false);
        
        const documentsHtml = documents.map(doc => {
            // 根据后端返回的数据结构获取文档属性
            const originalName = doc.originalName || '未知文件';
            const fileType = doc.fileType || '未知';
            const fileSize = this.formatFileSize(doc.fileSize || 0);
            const chunkCount = doc.chunkCount || 0;
            const status = this.formatStatus(doc.status);
            const createdTime = this.formatDate(doc.createdTime);
            const docId = doc.id || '';
            
            return `
                <tr>
                    <td class="document-name">${originalName}</td>
                    <td class="file-type">
                        <span class="file-type-badge">${fileType.toUpperCase()}</span>
                    </td>
                    <td class="file-size">${fileSize}</td>
                    <td class="chunk-count">${chunkCount}</td>
                    <td class="status">
                        <span class="status-badge status-${status.class}">${status.text}</span>
                    </td>
                    <td class="created-time">${createdTime}</td>
                    <td class="actions">
                        <button class="action-btn detail-btn" onclick="app.showDocumentDetail('${docId}')">
                            详情
                        </button>
                        <button class="action-btn delete-btn" onclick="app.showDeleteModal('${docId}', '${originalName.replace(/'/g, "\\'")}')">
                            删除
                        </button>
                    </td>
                </tr>
            `;
        }).join('');

        this.documentsTableBody.innerHTML = documentsHtml;
    }

    // 获取文件类型（移除图标，使用文本）
    getFileType(fileName) {
        if (!fileName || typeof fileName !== 'string' || fileName.trim() === '') {
            return '未知';
        }
        
        const parts = fileName.split('.');
        if (parts.length < 2) {
            return '文档';
        }
        
        const extension = parts.pop();
        if (!extension) {
            return '文档';
        }
        
        const typeMap = {
            'pdf': 'PDF',
            'doc': 'Word',
            'docx': 'Word',
            'txt': '文本',
            'md': 'Markdown'
        };
        return typeMap[extension.toLowerCase()] || '文档';
    }

    // 格式化日期
    formatDate(dateString) {
        if (!dateString) return '未知时间';
        
        try {
            const date = new Date(dateString);
            if (isNaN(date.getTime())) {
                return '无效日期';
            }
            
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            
            return `${year}-${month}-${day} ${hours}:${minutes}`;
        } catch (error) {
            console.error('Date formatting error:', error);
            return '格式错误';
        }
    }

    // 格式化文件大小
    formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    // 格式化状态
    formatStatus(status) {
        switch (status) {
            case '0':
                return { text: '正常', class: 'success' };
            case '1':
                return { text: '处理中', class: 'processing' };
            case '2':
                return { text: '失败', class: 'error' };
            default:
                return { text: '未知', class: 'unknown' };
        }
    }

    // 显示/隐藏加载状态
    showDocumentsLoading(show) {
        this.documentsLoading.style.display = show ? 'block' : 'none';
        if (show) {
            this.documentsTableBody.innerHTML = '';
            this.showEmptyState(false);
        }
    }

    // 显示/隐藏空状态
    showEmptyState(show) {
        this.emptyState.style.display = show ? 'block' : 'none';
        if (show) {
            this.documentsTableBody.innerHTML = '';
        }
    }

    // 显示删除确认模态框
    showDeleteModal(documentId, fileName) {
        this.currentDeleteId = documentId;
        this.deleteFileName.textContent = fileName;
        this.deleteModal.style.display = 'flex';
    }

    // 隐藏删除确认模态框
    hideDeleteModal() {
        this.deleteModal.style.display = 'none';
        this.currentDeleteId = null;
    }

    // 删除文档
    async deleteDocument() {
        if (!this.currentDeleteId) return;

        try {
            this.confirmDelete.disabled = true;
            this.confirmDelete.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 删除中...';

            const response = await fetch(`/ai/document/delete/${this.currentDeleteId}`, {
                method: 'DELETE'
            });

            if (response.ok) {
                const result = await response.json();
                if (result.code === 200) {
                    this.showToast('文档删除成功', 'success');
                    this.hideDeleteModal();
                    this.loadDocuments(); // 刷新列表
                } else {
                    throw new Error(result.msg || '删除失败');
                }
            } else {
                throw new Error('删除请求失败');
            }
        } catch (error) {
            console.error('Delete error:', error);
            this.showToast('删除失败: ' + error.message, 'error');
        } finally {
            this.confirmDelete.disabled = false;
            this.confirmDelete.innerHTML = '删除';
        }
    }

    // 显示上传弹框
    showUploadModal() {
        if (this.uploadModal) {
            this.uploadModal.style.display = 'flex';
            document.body.style.overflow = 'hidden';
        }
    }

    // 隐藏上传弹框
    hideUploadModal() {
        if (this.uploadModal) {
            this.uploadModal.style.display = 'none';
            document.body.style.overflow = 'auto';
        }
    }

    // 显示搜索弹框
    showSearchModal() {
        if (this.searchModal) {
            this.searchModal.style.display = 'flex';
            document.body.style.overflow = 'hidden';
            // 聚焦到搜索输入框
            setTimeout(() => {
                if (this.searchInput) {
                    this.searchInput.focus();
                }
            }, 100);
        }
    }

    // 隐藏搜索弹框
    hideSearchModal() {
        if (this.searchModal) {
            this.searchModal.style.display = 'none';
            document.body.style.overflow = 'auto';
        }
    }

    // 显示文档详情弹框
    async showDocumentDetail(documentId) {
        try {
            // 显示加载状态
            if (this.detailModal) {
                this.detailModal.style.display = 'flex';
                document.body.style.overflow = 'hidden';
                
                // 显示加载中状态，隐藏文档详情
                const detailLoading = window.document.getElementById('detailLoading');
                const documentDetail = window.document.getElementById('documentDetail');
                if (detailLoading) {
                    detailLoading.style.display = 'block';
                }
                if (documentDetail) {
                    documentDetail.style.display = 'none';
                }
            }

            // 调用后端接口获取文档详情
            const response = await fetch(`/ai/document/detail/${documentId}`);
            if (!response.ok) {
                throw new Error('获取文档详情失败');
            }

            const result = await response.json();
            if (result.code !== 200) {
                throw new Error(result.msg || '获取文档详情失败');
            }

            // 渲染文档详情
            this.renderDocumentDetail(result.data);

        } catch (error) {
            console.error('获取文档详情失败:', error);
            this.showToast('获取文档详情失败: ' + error.message, 'error');
            this.hideDetailModal();
        }
    }

    // 渲染文档详情
    renderDocumentDetail(document) {
        // 填充左侧文档信息
        window.document.getElementById('detailName').textContent = document.name || '未知';
        window.document.getElementById('detailOriginalName').textContent = document.originalName || '未知';
        window.document.getElementById('detailFileType').textContent = document.fileType || '未知';
        window.document.getElementById('detailFileSize').textContent = this.formatFileSize(document.fileSize || 0);
        window.document.getElementById('detailChunkCount').textContent = (document.chunkCount || 0) + ' 个';
        window.document.getElementById('detailStatus').textContent = this.formatStatus(document.status || 'UNKNOWN').text;
        window.document.getElementById('detailCreatedTime').textContent = this.formatDate(document.createdTime);
        window.document.getElementById('detailUpdatedTime').textContent = this.formatDate(document.updatedTime);
        
        // 填充右侧文档块列表
        const chunksList = window.document.getElementById('chunksList');
        const chunksHtml = document.chunks && document.chunks.length > 0 
            ? document.chunks.map(chunk => `
                <div class="chunk-item">
                    <div class="chunk-header">
                        <span class="chunk-id">块 #${chunk.id}</span>
                        <span class="chunk-size">${chunk.text ? chunk.text.length : 0} 字符</span>
                    </div>
                    <div class="chunk-content">${chunk.text || '无内容'}</div>
                </div>
            `).join('')
            : '<div class="no-chunks">暂无文档块</div>';
        
        chunksList.innerHTML = chunksHtml;
        
        // 隐藏加载状态，显示文档详情内容
        const detailLoading = window.document.getElementById('detailLoading');
        const documentDetail = window.document.getElementById('documentDetail');
        
        if (detailLoading) {
            detailLoading.style.display = 'none';
        }
        if (documentDetail) {
            documentDetail.style.display = 'block';
        }
    }

    // 隐藏文档详情弹框
    hideDetailModal() {
        if (this.detailModal) {
            this.detailModal.style.display = 'none';
            document.body.style.overflow = 'auto';
        }
    }

    // 显示消息提示
    showToast(message, type = 'success') {
        if (!this.toast) {
            console.error('Toast element not found');
            return;
        }

        this.toast.className = `toast ${type}`;
        const messageElement = this.toast.querySelector('.toast-message');
        if (messageElement) {
            messageElement.textContent = message;
        }
        
        this.toast.style.display = 'block';

        // 3秒后自动隐藏
        setTimeout(() => {
            this.toast.style.display = 'none';
        }, 3000);
    }
}

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    window.app = new KnowledgeBaseApp();
});

// 页面卸载前清理
window.addEventListener('beforeunload', () => {
    // 清理可能的定时器或未完成的请求
});